<template>
  <a-modal :width="500" :title="title" v-model="visible" :maskClosable="false" :confirmLoading="loading" @ok="onSubmit" @cancel="() => (visible = false)">
    <a-skeleton active :paragraph="{ rows: 6 }" :loading="initLoading">
      <a-spin :delay="100" :spinning="loading">
        <a-form-model ref="sjhtform" :model="form" :rules="rules" :labelCol="lcol" :wrapperCol="wcol" @submit.stop="onSubmit">
          <a-form-model-item label="姓名" prop="trueName">
            <a-input v-model="form.trueName" allowClear :maxLength="8" placeholder="请输入姓名" />
          </a-form-model-item>
          <a-form-model-item label="手机号" prop="mobilePhone">
            <a-input v-model="form.mobilePhone" allowClear :maxLength="11" placeholder="请输入手机号码" />
          </a-form-model-item>
          <a-form-model-item label="用户名" prop="userName">
            <a-input v-model="form.userName" allowClear :maxLength="16" placeholder="请输入用户名" />
          </a-form-model-item>
          <a-form-model-item label="登录密码" prop="password" v-if="!form.id">
            <a-input-password v-model="form.password" allowClear :maxLength="32" placeholder="请输入登录密码" />
          </a-form-model-item>
          <a-form-model-item label="组织机构" prop="orgId">
            <a-tree-select v-model="form.orgId" allowClear :tree-data="treeData" treeDataSimpleMode placeholder="请输入组织机构" />
          </a-form-model-item>
          <a-form-model-item label="用户角色" prop="roleId">
            <a-select v-model="form.roleId" mode="multiple" placeholder="请输入角色（支持多选）">
              <a-select-option v-for="o in options.role" :key="o.id">{{o.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-skeleton>
  </a-modal>
</template>
<script>
import md5 from 'js-md5'
import { pick } from 'lodash'
import { Skeleton, TreeSelect } from 'ant-design-vue'
import { form } from '@/utils/mixins'
import regexp from '@/utils/validate'
import { SaveUser, UpdateUser } from '@/api/manage/user'
import { GetOrgList } from '@/api/manage/org'
import { OptionsRole } from '@/api/manage/role'
export default {
  name: 'SjhtUserForm',
  components: {
    [Skeleton.name]: Skeleton,
    [TreeSelect.name]: TreeSelect
  },
  mixins: [form],
  data() {
    return {
      initLoading: true,
      options: { org: [], role: [] },
      rules: {
        trueName: [
          { required: true, whitespace: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 8, message: '请输入正确的姓名字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (regexp.name(value)) callback()
              else callback('请输入正确的姓名')
            },
            trigger: 'blur'
          }
        ],
        mobilePhone: [
          { required: true, whitespace: true, message: '请输入手机号' },
          { pattern: regexp.phone, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        userName: [{ required: true, whitespace: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, whitespace: true, message: '请输入登录密码', trigger: 'blur' }],
        orgId: [{ required: true, message: '请选择组织机构', trigger: 'blur' }],
        roleId: [{ required: true, type: 'array', message: '请选择用户角色', trigger: 'blur' }]
      }
    }
  },
  computed: {
    treeData: function () {
      if (this.options?.org.length > 0) {
        return this.options.org.map(m => ({ id: m.id, pId: m.parentId, value: m.id, label: m.orgName }))
      } else return []
    }
  },
  methods: {
    // 打开新建窗口
    create() {
      this.visible = true
      if (this.loading) return
      this.initOptions()
      this.reset()
      this.title = '新建用户'
      this.form = {}
    },
    // 打开修改窗口
    update(data) {
      this.visible = true
      if (this.loading) return
      this.initOptions()
      this.reset()
      this.title = `修改【${data.trueName}】用户`
      const dd = pick(data, ['id', 'trueName', 'userName', 'mobilePhone', 'orgId'])
      if (data.roleId) {
        Object.assign(dd, { roleId: data.roleId.split(',') })
      }
      this.form = dd
    },
    // 初始化选项
    initOptions() {
      const { options } = this
      if (options.org.length <= 0 || options.role.length <= 0) {
        this.initLoading = true
        Promise.all([GetOrgList(), OptionsRole()])
          .then(([org, role]) => {
            options.org = org
            options.role = role
          })
          .catch(err => {
            this.$message.error(err)
          })
          .finally(() => {
            this.initLoading = false
          })
      }
    },
    // 点击确定
    onSubmit(e) {
      e.preventDefault()
      this.$refs.sjhtform.validate(valid => {
        if (!valid) return false
        const { form } = this
        const addUser = this.$store.state?.user?.name
        Object.assign(form, { addUser,password: md5(form.password + form.userName), })
        if (form.id) {
          this.submit(UpdateUser, form)
        } else this.submit(SaveUser, form)
      })
    }
  }
}
</script>